let text = require('../../../../common/util/text.js')
const utils = require('../../../../common/util/util')
var timerInterval;
Page({
  data: {
      xPageReady : true ,
      xActicle : '' ,
      education_content_id:'',
      time:0,
      send:true,
      videoContext:'',
      is_first:true,
      disabled:true,
      day:1,
      nav: [
        {
          title: '最新',
          key: ''
        },
        {
          title: '最热',
          key: ''
        }
      ],
      active: 0,
      page: 1,
      warning: true,
      list:[],
      focus:false,
      input:'',
      isLike:false,
      navbarInitTop:true
  },
  onReady:function(){
    this.videoContext = wx.createVideoContext('myVideo')
  },
  xChildReload: function () {
    var pages = getCurrentPages();  //当前页面栈
    if ( pages.length > 1 ) {
      var beforePage = pages[ pages.length - 2 ];  //获取上一个页面实例对象
      beforePage.xInit();  //触发父页面中的方法
    }
  },
  onLoad: function (options) {
      let that =this
      that.setData({
        education_content_id:options.education_content_id,
        week:Number(options.week),
        day:options.day?Number(options.day):1,
        openid:getApp().globalData.xCustomer.openId
      })
      that.xInit(options.week,options.day)
      that.xList()
  },
  onShareAppMessage: function () {
    return {
      title: this.data.xActicle.title
    };
  },
  xSaveShowStateFocus: function () {
    this.setData({
      xSaveShowState: true,
      focus:true
    })
  },
  xSaveShowStateBlur: function (e) {
    let value = e.detail.value
    this.setData({
      focus:false
    })
    if (value === '') {
      this.setData({
        xSaveShowState: false
      })
    }
  },
  xSave:function(){
    let that = this
    that.setData({
      disabled:true
    })
    let data = {
      text_content:that.data.input,
      indoctrination_id:that.data.education_content_id,
      week:that.data.week,
      day:that.data.day
    }
    wx.cloud.callFunction({
        name: 'dynamic_content',
        data: {
            action: "add_dynamic_content",
            dataObj: data
        }
    }).then(res => {
      wx.showToast({
        title: '成功',
        icon: 'none',
      })
      that.setData({
        input:'',
        page:1,
        list:[]
      })
      that.xList()
    })
  },
  xInput: function (e) {
    let that = this
    let value = e.detail.value
    that.setData({
      input: value,
      disabled:false
    })
  },
  xToDetail: function (e) {
    let id = e.currentTarget.dataset.id
    let openid = e.currentTarget.dataset.openid
    let totalcomment = e.currentTarget.dataset.totalcomment
    wx.navigateTo({
      url: '/subtool/pages/community/detail/index?id=' + id + '&openid=' + openid +'&totalcomment='+ totalcomment,
    })
  },
  xList: function () {
    let that = this
    let active = that.data.active
    let page = that.data.page
    let list = that.data.list
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "get_dynamic_content_list",
        page_number: page,
        type: active + 1,
        indoctrination_id:that.data.education_content_id
      }
    }).then(res => {
      let data = res.result
      for (var i in data) {
        data[i].release_time = utils.formatTime_emotion(new Date(data[i].release_time))
        list.push(data[i])
      }
      if (data.length === 0) {
        that.setData({
          list: list,
          page: page,
          loading: false,
          warning: true
        })
        setTimeout(() => {
          that.setData({
            warning: true
          })
        }, 2000)
      } else {
        page += 1
        that.setData({
          list: list,
          page: page,
          loading: false,
          page: page,
        })
      }
      console.log(that.data.list)
      wx.hideLoading()
    })
  },
  xLike: function (e) {
    let that = this
    let id = that.data.id
    let params = e.currentTarget.dataset
    wx.cloud.callFunction({
      name: 'dynamic_content',
      data: {
        action: "thumbs_up",
        _id: params.id
      }
    }).then(res => {
      if (!params.state) {
        wx.showToast({
          title: '点赞成功',
          icon: 'none'
        })
        that.setData({
          [`list[${params.index}].total_thumbs_up`]:Number(that.data.list[params.index].total_thumbs_up)+1,
          [`list[${params.index}].me_thumbs_up`]:true
        })
      } else {
        wx.showToast({
          title: '取消成功',
          icon: 'none'
        })
        that.setData({
          [`list[${params.index}].total_thumbs_up`]:Number(that.data.list[params.index].total_thumbs_up)-1,
          [`list[${params.index}].me_thumbs_up`]:false
        })
      }
    })
  },
  xNavSelect: function (e) {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    let id = that.data.id
    let key = e.currentTarget.dataset.key
    that.setData({
      active: key,
      page: 1,
      list: [],
      loading: true,
      state:e.currentTarget.dataset.state
    })
    wx.pageScrollTo({
      scrollTop:  that.data.navbarInitTop,
    })
    that.xList()
  },
  xParReload: async function () {
    console.log('我执行了')
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    let active = that.data.active
    let page = that.data.page
    let list = []
    for (var i = 0; i < page; i++) {
      await wx.cloud.callFunction({
        name: 'dynamic_content',
        data: {
          action: "get_dynamic_content_list",
          type: active + 1,
          page_number: i + 1,
          indoctrination_id:that.data.education_content_id
        }
      }).then(res => {
        let data = res.result
        for (var k in data) {
          data[k].release_time = utils.formatTime_emotion(new Date(data[k].release_time))
          list.push(data[k])
        }
        that.setData({
          list: list
        })
        wx.hideLoading()
      })
    }
  },
  xDelete:function(e){
    let that =this
    let _id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let _data = {
        is_delete:1
    }
    wx.showModal({
      content: '确认删除留言吗？',
      title: '警告',
      cancelText: '取消',
      confirmText: '确定',
      success: (res) => {
        if (res.confirm) {
          that.setData({
            [`list[${index}].is_delete`]: true,
          })
          wx.cloud.callFunction({
            name: 'dynamic_content',
            data: {
              action: "update_dynamic_content",
              _id: _id,
              dataObj: _data
            }
          }).then(res => {
            // that.xParReload()
          })
        }
      }
    })
    
  },
  xToEdit:function(e){
    let that = this
    let index  = e.currentTarget.dataset.index
    that.setData({
      input:that.data.list[index].text_content
    })
  },
  xInit: async function (week,day) {
    let that = this
    await wx.cloud.callFunction({
        name: 'digital_therapy',
        data: {
            action: "get_cognitive_education_content_day",
            dataObj: {
              week:Number(week),
              day:Number(day)
            }
        }
    }).then(res => {
      for(let index in res.result){
        if(res.result[index]._id==that.data.education_content_id){
          res.result[index].content=text.text(res.result[index].content)
          that.setData({
              xActicle : res.result[index] 
          })
          break;
        }
      }
    })
    
    that.setData({
        xPageReady : false
    })

  },
  onPlay:function(e){
    let that =this;
    // const current_time = wx.getStorageSync(this.data.education_content_id +'_video')
    // if(current_time && that.data.is_first){
    //   that.videoContext.seek(current_time)
    // }
    // that.setData({
    //   is_first:false
    // })
  },
  onPause:function(e){
    
  },
  onEnded:function(e){
    wx.removeStorageSync(this.data.education_content_id +'_video')
    this.xSub()
  },
  onTimeupdate:function(e){
    wx.setStorageSync(this.data.education_content_id +'_video', e.detail.currentTime)
  },
  xSub : function () {
    let that = this
      let _dataObj ={
        week: that.data.week ,
        content_id: that.data.education_content_id ,
        is_read: true ,
        read_duration: that.data.time,
        day:that.data.day,
        education_content_id:that.data.education_content_id
    }
    wx.cloud.callFunction({
        name: 'digital_therapy',
        data: {
            action: "add_education_reading_record",
            dataObj: _dataObj
        }
    }).then( res => {
        that.xChildReload()
    })
  }
})